﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraBars;
using DevExpress.XtraNavBar;
using DevExpress.XtraTab;
using DevExpress.XtraTab.ViewInfo;
using ECRMS.WinForm.Modules;
using System.Reflection;
using ECRMS.WinForm.BaseClass;
using DevExpress.XtraEditors;
using System.Data.Linq;
using DevExpress.Utils;
using ECRMS.WinForm.BaseClass.Xml;
using ECRMS.WinForm.Properties;

namespace ECRMS.WinForm
{
    public partial class MainForm : BaseForm
    {
        public Core core = Core.getInstance();

        public BarSubItem styleItemBar = null;
        public BarSubItem langItemBar = null;
        public BarSubItem userItemBar = null;

        public MainForm()
        {
            core.CreateWaitDialog("初始化主界面", "主界面");
            InitializeComponent();
            //主窗体设置
            InitView();
            //初始化上端菜单栏
            core.SetWaitDialogCaption("初始化模块");
            InitMenu();
            //根据权限，初始化左边功能菜单
            InitNavBar();
            //事件注册
            InitEventHandler();
            core.CloseWaitDialog();
            core.CoreMainForm = this;
        }

        private void InitEventHandler()
        {
            //上端菜单栏，点击事件注册
            barManager.ItemClick += new ItemClickEventHandler(barManager_ItemClick);  
   
            //左边功能模块菜单，点击事件注册
            navBarControl.LinkClicked += new NavBarLinkEventHandler(NavBar_LinkClicked);
           
            //tab页closeButton点击事件
            xtraTabControl.CloseButtonClick += new EventHandler(xtraTabControl1_CloseButtonClick);

            //语言切换监听
            core.LangChanged += new Core.LanguageChangedHandler(this.ChangeLanguage);
        }

        void xtraTabControl1_CloseButtonClick(object sender, EventArgs e)
        {
            XtraTabControl tabControl = sender as XtraTabControl;
            ClosePageButtonEventArgs arg = e as ClosePageButtonEventArgs;
            XtraTabPage colseTabPage = (arg.Page as XtraTabPage);

            //第一种方案 隐藏
            //colseTabPage.PageVisible = false;

            //第二种方案 销毁掉(这边销毁的的代码不知道对不对，因为测试的时候内存的大小变化不大)
            colseTabPage.Controls.Clear();
            colseTabPage.Dispose();
        }
        /// <summary>
        /// 初始化导航栏
        /// </summary>
        public void InitNavBar()
        {
            //假设有以下这些权限
            int[] userAuthoritys= new int[]{11,21,22,23,31,32,41,51,52,53,54};

            navBarControl.BeginUpdate();

            foreach (int auth in userAuthoritys)
            {
                if (navBarControl.Groups[(auth / 10).ToString()] == null)
                {
                    CreateNavBarGroup(auth);
                }
                CreateNavBarItem(auth);
            }
            navBarControl.EndUpdate();

            //创建首页
            ShowTabPanelByItemName("0", "首页", false);
        }

        //根据权限id创建BarItem
        private void CreateNavBarItem(int auth)
        {
            navBarControl.Groups[auth / 10 - 1].ItemLinks.Add(
              new NavBarItem()
              {
                  Caption = ModuleEnum.GetName(typeof(ModuleEnum), auth),
                  Name = auth.ToString(),
                  SmallImage=baseImageStore32.Images[auth.ToString()]
                  //SmallImage=baseImageStore32.Images[0]
              }
           );
        }

        //根据权限id创建BarGroup
        private void CreateNavBarGroup(int auth)
        {
            NavBarGroup navBarGroup = new NavBarGroup() { Expanded = true, Name = (auth / 10).ToString(), Caption = GetModuleStrByPower("_" + (auth / 10).ToString(), core.CoreLanguage) };//GroupEnum.GetName(typeof(GroupEnum),auth / 10)
            navBarControl.Groups.Add(navBarGroup);
        }


        void NavBar_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            string itemName = e.Link.ItemName;
            string itemCaption = e.Link.Caption;
            try
            {
            ShowTabPanelByItemName(itemName, itemCaption);

            }
            catch (Exception)
            {
                  XtraMessageBox.Show(this,"系统异常","报错");
                  return;
            }
        }

        private void ShowTabPanelByItemName(string itemName, string itemCaption, bool showCloseButton = true)
        {
            xtraTabControl.BeginUpdate();
            XtraTabPage tab = xtraTabControl.TabPages.FirstOrDefault(p => p.Name == itemName);
           if (tab == null)
            {
                tab = CreateNewTabPanel(itemCaption, itemName);
                if (tab == null)
                {
                    xtraTabControl.EndUpdate();
                    return;
                }
                else
                { 
                    tab.ShowCloseButton = (showCloseButton == true ? DefaultBoolean.True : DefaultBoolean.False);
                    xtraTabControl.TabPages.Add(tab);
                }
            }
            xtraTabControl.SelectedTabPage = tab;
            xtraTabControl.EndUpdate();
        }

        /// <summary>
        /// 创建一个tab页，把相应的module加进tab
        /// </summary>
        /// <param name="itemCaption"></param>
        /// <param name="itemName"></param>
        /// <returns></returns>
        private XtraTabPage CreateNewTabPanel(string itemCaption, string itemName)
        {
            XtraTabPage newTab = new XtraTabPage()
            {
                Text = itemCaption,
                Name = itemName,
                Image=baseImageStore24.Images[itemName]
            };
            Assembly assembly = typeof(MainForm).Assembly;
            Type t = null;
            foreach (Type type in assembly.GetTypes())
            {
                if (type.IsDefined(typeof(ModuleInstanceAttribute), false))
                {
                    var attributes = type.GetCustomAttributes(typeof(ModuleInstanceAttribute), false);
                    foreach (var obj in attributes)
                    {
                        var attribute = obj as ModuleInstanceAttribute;
                        if (itemName == attribute.Name)
                        {
                            t = type;
                            break;
                        }
                    }
                }
                if (t != null)
                {
                    break;
                }
            }
            if (t != null)
            {
                var instance = Activator.CreateInstance(t) as XtraUserControl;
                instance.Dock = DockStyle.Fill;
                newTab.Controls.Add(instance);
                return newTab;
            }
            else
            { 
                return null;
            }
        }

        /// <summary>
        /// 初始化导航菜单
        /// </summary>
        private void InitMenu()
        {
            barManager.BeginUpdate();

            barManager.MainMenu = MenuBar;
            barManager.Categories.Add("style");//主题类
            barManager.Categories.Add("lang");//语言类
            barManager.Categories.Add("close");//用户退出系统
            barManager.Categories.Add("logoff");//用户注销

            this.styleItemBar = new BarSubItem(barManager, "主题选择");
            this.langItemBar = new BarSubItem(barManager, "语言选择");
            this.userItemBar = new BarSubItem(barManager,"用户");

            //主题
            foreach (DevExpress.Skins.SkinContainer skin in DevExpress.Skins.SkinManager.Default.Skins)
            {
                BarButtonItem buttonItem = new BarButtonItem(barManager, skin.SkinName);
                buttonItem.Category = barManager.Categories["style"];
                this.styleItemBar.AddItem(buttonItem);
            }
            //语言
            BarButtonItem chButtonItem = new BarButtonItem(barManager, LangEnum.中文.ToString());
            BarButtonItem enButtonItem = new BarButtonItem(barManager, LangEnum.英文.ToString());
            chButtonItem.Category=barManager.Categories["lang"];
            enButtonItem.Category = barManager.Categories["lang"];
            this.langItemBar.AddItem(chButtonItem);
            this.langItemBar.AddItem(enButtonItem);
            //用户
            BarButtonItem changeButtonItem = new BarButtonItem(barManager,"注销");
            BarButtonItem exitButtonItem = new BarButtonItem(barManager, "退出");
            BarButtonItem modifyPassButtonItem = new BarButtonItem(barManager, "修改密码");
            changeButtonItem.Category = barManager.Categories["logoff"];
            exitButtonItem.Category = barManager.Categories["close"];
            modifyPassButtonItem.Category = barManager.Categories["modifypassword"];
            this.userItemBar.AddItem(changeButtonItem);
            this.userItemBar.AddItem(exitButtonItem);

            MenuBar.AddItems(new BarItem[] { styleItemBar, langItemBar,userItemBar });
            barManager.EndUpdate();

        }
        /// <summary>
        /// 菜单栏选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void barManager_ItemClick(object sender, ItemClickEventArgs e)
        {
            BarSubItem subMenu = e.Item as BarSubItem;
            if (subMenu != null)
            {
                return;
            };
            BarButtonItem buttonItem = e.Item as BarButtonItem;
            switch (buttonItem.Category.Name)
            {
                case "style":
                    BaseForm.defaultLookAndFeel.LookAndFeel.SkinName = e.Item.Caption;
                    core.CoreUserMode.SetChildNodeText("style", e.Item.Caption);
                    break;
                case "lang":
                    core.ChangeLanguage((LangEnum)Enum.Parse(typeof(LangEnum),buttonItem.Caption));
                    core.CoreUserMode.SetChildNodeText("language", buttonItem.Caption);
                    break;
                case "close":
                    Application.Exit();
                    break;
                case "logoff":
                    xtraTabControl.BeginUpdate();
                    xtraTabControl.TabPages.Clear();
                    xtraTabControl.EndUpdate();

                    navBarControl.BeginUpdate();
                    navBarControl.Items.Clear();
                    navBarControl.EndUpdate();
                    core.CoreMainForm.Hide();
                    core.CoreLoginForm.Show();
                    break;
                case "closemodifypassword":
                    //待做....
                    break;
                default:
                    break;
            }
           
        }
        /// <summary>
        /// 初始化窗体
        /// </summary>
        private void InitView()
        {

            this.ClientSize = new System.Drawing.Size(990, 660);
            this.Icon = ResourceImageHelper.CreateIconFromResources("ECRMS.WinForm.LayoutMainDemo.ico", typeof(MainForm).Assembly);
            this.pictureBox1.Image = ECRMS.WinForm.Properties.Resources.logo;


            //设置用户定制的主题和语言
            //XMLReader xr = new XMLReader("CustomMode.xml", "UserMode");

            //标题、登录信息等的语言设置
            //core.CoreLanguage = (LangEnum)Enum.Parse(typeof(LangEnum), xr.GetChildNodeText("language"));
            ChangeLanguage(core.CoreLanguage);
          
            //BaseForm.defaultLookAndFeel.LookAndFeel.SkinName = xr.GetChildNodeText("style");

            //设置tab中有close按钮
            xtraTabControl.ClosePageButtonShowMode = ClosePageButtonShowMode.InAllTabPageHeaders;

        }

        /// <summary>
        /// 根据权限获得模块名称
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private string GetModuleStrByPower(string str,LangEnum lang)
        {
            switch (lang)
            {
                case LangEnum.China:
                case LangEnum.中文:
                    return Language_ch.ResourceManager.GetString(str);
                    break;
                case LangEnum.English:
                case LangEnum.英文:
                    return Language_en.ResourceManager.GetString(str);
                    break;
                default:
                    return "";
                    break;
            }
        }

        private void ChangeLanguage(LangEnum lang)
        {
            foreach (NavBarGroup item in navBarControl.Groups)
            {
                item.Caption = GetModuleStrByPower("_" + item.Name, lang);
            }
            switch (lang)
            {
                case LangEnum.China:
                case LangEnum.中文:
                    this.Text = Language_ch.text;
                    this.lbl_title.Text = Language_ch.title;
                    break;
                case LangEnum.English:
                case LangEnum.英文:
                    this.Text = Language_en.text;
                    this.lbl_title.Text = Language_en.title;
                    break;
                default:
                    break;
            }
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }
    }
}
